import queue

import librosa
import numpy as np
import sounddevice as sd
from scipy.signal import resample


def get_sample_rate(device_id):
    device_info = sd.query_devices(device_id, 'input')
    return device_info['default_samplerate']


def record_from_audio_device(duration, device_id, channels, wait=True):
    sd.default.device = device_id
    sd.default.channels = channels
    fs = get_sample_rate(device_id)
    recording = sd.rec(int(duration * fs), samplerate=fs)
    if wait:
        sd.wait()
    return recording


def streaming_record(device_id, channels):
    block_length = 1000
    fs = get_sample_rate(device_id)
    q = queue.Queue()

    def audio_callback(indat, frames, time, status):
        nonlocal q
        q.put(indat)

    buf = []
    input_length = 0
    data = np.zeros(block_length)

    with sd.InputStream(device=device_id, channels=channels, samplerate=fs, callback=audio_callback):
        while True:
            if not q.empty():
                indata = q.get_nowait()
                if len(indata.shape) != 2:
                    continue
            else:
                continue
            exc = block_length - (input_length + indata.shape[0])

            if exc > 0:
                buf.append(indata)
                input_length += indata.shape[0]
            else:
                if exc == 0:
                    later = None
                    buf.append(indata)
                else:
                    later = indata[exc:, ...]
                    buf.append(indata[:exc, ...])
                # np.concatenate(buf)
                data = librosa.to_mono(resample(np.concatenate(buf).transpose((1, 0)), 1000))
                print(data[19])
                buf.clear()
                if later is not None:
                    buf.append(later)
                    input_length = exc
                else:
                    input_length = 0




streaming_record(19, 2)
